<template>
  <scroll-view
    class="box"
    scroll-y="true"
    enhanced
    :show-scrollbar="false"
    enable-flex="true">
    <template v-if="desserts.length > 0">
      <view class="edit" @click="editCart" v-if="optionMsg === '编辑'">
        {{ optionMsg }}
      </view>
      <view class="edit" @click="doneCart" v-else>{{ optionMsg }}</view>
      <block v-for="(item, index) in cartList" :key="item.dessertId">
        <view
          class="dessert-detail"
          @touchstart="touchStart($event, item, index)"
          @touchmove="touchMove($event, item)"
          @touchend="touchEnd($event, item)"
          :style="{
            transform:
              currentIndex === index ? 'translateX(' + item.moveX + 'px)' : 0,
            transition: 'all 0.4s',
          }">
          <view class="content">
            <view class="detail-left" @click="goDessertDetail(item)">
              <view class="dessert-left">
                <up-checkbox-group
                  @change="checkboxChange(item), getDelItem(item)">
                  <up-checkbox :checked="item.flag" activeColor="#f9acb4" />
                </up-checkbox-group>
                <image
                  :src="`http://localhost:8080/api/files/${item.dessert.dessertImg || ''}`"
                  style="
                    width: 130rpx;
                    height: 130rpx;
                    margin-left: 10rpx;
                  "></image>
              </view>
              <view class="dessert-size">
                <text
                  style="
                    font-size: 28rpx;
                    font-weight: bold;
                    white-space: nowrap;
                  ">
                  {{ item.dessert.dessertName || '无'}}
                </text>
                <text style="font-size: 25rpx">{{ item.dessert.specs || '无'}}/份</text>
                <text class="dessert-price">￥{{ item.dessert.dessertPrice || '无'}}</text>
              </view>
            </view>
            <view class="detail-right">
              <text class="sub" @click="reduce(item)">-</text>
              <text class="num">{{ item.num }}</text>
              <text class="add" @click="add(item)">+</text>
            </view>
          </view>
          <view class="delete-btn">
            <view class="delete-text" @touchend.stop @click="delCartItem(item)">
              删除
            </view>
          </view>
        </view>
      </block>
      <view style="width: 100%; height: 100rpx"></view>
    </template>
    <template v-else>
      <view
        style="
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          height: 700rpx;
          color: #666;
          margin: auto;
          padding-top: 10rpx;
        ">
        <image
          src="../../static/icon/cartBig.png"
          style="width: 400rpx; height: 400rpx"></image>
        <text style="text-align: center">购物车空空如也~</text>
      </view>
    </template>
  </scroll-view>
  <view class="fotter">
    <view class="fotter-left">
      <up-checkbox-group @change="selectedAll">
        <up-checkbox label="全选" :checked="allChecked" activeColor="#f9acb4" />
      </up-checkbox-group>
      <view style="margin: auto 0" v-if="optionMsg === '编辑'">
        总计:
        <text style="color: #7e675b; font-weight: bold">
          ￥{{ totalMoney.toFixed(2) }}
        </text>
      </view>
    </view>
    <view class="fotter-right" @click="settlement" v-if="optionMsg === '编辑'">
      {{ '结算( ' + totalNum + ' )' }}
    </view>
    <view class="fotter-right" @click="batchDelCart" v-else>删除</view>
  </view>
</template>

<script setup>
import { computed, ref } from 'vue'
import { useUserStore } from '../../stores/user.js'
import { useCartStore } from '../../stores/cart.js'
import {
  updateCartService,
  getCartByUserId,
  delCartItemService,
  batchDeleteCart,
} from '../../api/cart.js'
import { getDessertByIdService } from '../../api/dessert.js'
import { debounce } from '../../uni_modules/uview-plus/index.js'
import { onLoad, onHide, onShow } from '@dcloudio/uni-app'
import { array } from '../../uni_modules/uview-plus/libs/function/test.js'
const cartStore = useCartStore()
const userStore = useUserStore()

const optionMsg = ref('')

const desserts = ref([])
const cartList = ref([])
const getCartInfo = async () => {
  cartList.value = []
  const res = await getCartByUserId(userStore.userInfo.userId)
  desserts.value = res.data ? res.data : []
  
  if(res.data.length <= 0) {
    allChecked.value = false
  }
  
  if (desserts.value) {
    cartStore.setCar(desserts.value)
    cartStore.setGoodsNum(desserts.value.length)
    
    // 遍历获取具体的甜品数据
    desserts.value.forEach(async (item) => {
        const dd = await getDessertByIdService(item.dessertId)
        if(dd.code == 0)
        {
          item.dessert = dd.data || []
          item.flag = true
        }
        cartList.value.push(item)
    })
  }
}


const setDesserts = () => {
  desserts.value.forEach((item) => {
    item.moveX = 0
  })
}
const allChecked = ref(true)
// 复选框选中事件
const checkboxChange = (item) => {
  // 复选框原来选中的点击变为不选中false
  if (item.flag === true) {
    item.flag = false
  } else {
    item.flag = true
  }
  // 复选框全选时，全选按钮选中
  let newArr = []
  desserts.value.map((item) => {
    if (item.flag) {
      newArr.push(item)
    }
  })
  if (newArr.length === desserts.value.length) {
    allChecked.value = true
  } else {
    allChecked.value = false
  }
}

// 全选按钮选择事件
const selectedAll = () => {
  if (allChecked.value === true) {
    allChecked.value = false
    // 遍历甜品全部不选中
    desserts.value.forEach((item) => {
      item.flag = false
    })
  } else {
    allChecked.value = true
    // 遍历甜品全部选中
    desserts.value.forEach((item) => {
      item.flag = true
    })
  }
}

// 加甜品
const add = async (item) => {
  item.moveX = 0
  let num = item.num
  item.num = num + 1
  await updateCartService(item)
}

// 减甜品
const reduce = async (item) => {
  item.moveX = 0
  let num = item.num
  if (num > 1) {
    num -= 1
  } else if ((num = 1)) {
    uni.showToast({
      title: '甜品数量不能少于1',
      icon: 'none',
    })
  }
  item.num = num
  await updateCartService(item)
}

// 甜品总数量
const totalNum = computed(() => {
  let totalNum = 0
  desserts.value.map((item) => {
    item.flag ? (totalNum += item.num) : (totalNum += 0)
  })
  return totalNum
})
// 甜品总价格
const totalMoney = computed(() => {
  let totalMoney = 0
  desserts.value.map((item) => {
    item.flag ? (totalMoney += item.num * item.dessert.dessertPrice) : (totalMoney += 0)
  })
  return totalMoney
})

// 点击跳转到甜品详情页
const goDessertDetail = (item) => {
  uni.navigateTo({
    url:
      '/pages/dessertDetail/dessertDetail?id=' +
      encodeURIComponent(JSON.stringify(item.dessertId)),
  })
}
onShow(() => {
  getCartInfo()
  optionMsg.value = '编辑'
  uni.$on('update')
})
onHide(() => {
  uni.$off('update')
})

/* 左滑删除 */
const startX = ref(0)
const btnWidth = ref(80)
const currentIndex = ref(0)
const itemTransLateX = ref(0)
// 触摸动作开始
const touchStart = (event, item, index) => {
  currentIndex.value = index
  // 手指点击屏幕距离左侧的距离值
  startX.value = event.touches[0].clientX
}
// 触摸移动事件
const timer = ref(null)
const touchMove = (event, item) => {
  if (timer.value != null) {
    clearTimeout(timer.value)
  }
  timer.value = setTimeout(() => {
    // 滑动距离减去手指初始触摸的距离
    let dis = event.touches[0].clientX - startX.value
    item.moveX = dis
    if (item.moveX > 0) {
      // 右滑不允许
      item.moveX = 0
    } else {
      // 左滑
      if (item.moveX < -btnWidth.value / 2) {
        item.moveX = -btnWidth.value
      }
    }
  }, 200)
}
// 手指离开事件
const touchEnd = (event, item) => {
  if (Math.abs(item.moveX) < btnWidth.value / 2) {
    item.moveX = 0
  } else {
    item.moveX = -btnWidth.value
  }
}

// 删除按钮点击事件
const delCartItem = (item) => {
  uni.showModal({
    title: '温馨提示',
    content: '您确定要将选中甜品移出购物车吗？',
    success: async (res) => {
      if (res.confirm) {
        const res = await delCartItemService(item.id)
        if (res.code === '0') {
          uni.showToast({
            title: '删除成功',
            icon: 'none',
          })
          getCartInfo()
          cartStore.setCar(desserts.value)
          cartStore.setGoodsNum(desserts.value.length)
        }
      } else {
        item.moveX = 0
      }
    },
  })
}

// 点击编辑管理购物车
const editCart = () => {
  optionMsg.value = '完成'
  desserts.value.forEach((item) => (item.flag = false))
  allChecked.value = false
}

const delList = ref([])
const getDelItem = (item) => {
  delList.value = desserts.value.filter((item) => item.flag === true)
}
const batchDelCart = async () => {
  uni.showModal({
    title: '温馨提示',
    content: '您确定要将这些甜品移出购物车吗？',
    success: async (res) => {
      if (res.confirm) {
        const res = await batchDeleteCart(delList.value)
        if (res.code === '0') {
          uni.showToast({
            title: '删除成功',
            icon: 'none',
          })
          getCartInfo()
          cartStore.setCar(desserts.value)
          cartStore.setGoodsNum(desserts.value.length)
          desserts.value.forEach((item) => (item.flag = false))
        }
      }
    },
  })
  getCartInfo()
}

// 完成编辑
const doneCart = () => {
  optionMsg.value = '编辑'
  desserts.value.forEach((item) => (item.flag = true))
  allChecked.value = true
}

// 确认订单（下单）
const settlement = () => {
  let confirmDessert = []
  desserts.value.map((item) => {
    if (item.flag) {
      confirmDessert.push(item)
    }
  })
  if (confirmDessert.length <= 0) {
    uni.showToast({
      title: '您还未选择下单甜品',
      icon: 'none',
    })
    return
  }
  uni.navigateTo({
    url: `/pages/bookOrder/bookOrder?buy=${encodeURIComponent(
      JSON.stringify(confirmDessert)
    )}`,
  })
}
</script>

<style lang="scss" scoped>
.edit {
  width: 80rpx;
  height: 50rpx;
  background-color: #fff;
  color: #000;
  font-size: 28rpx;
  float: right;
  box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.08);
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
}
.dessert-detail {
  width: 100%;
  height: 180rpx;
  margin: 10rpx auto;
  box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.08);
  border-radius: 20rpx;
  display: flex;
  padding: 30rpx 15rpx 30rpx 30rpx;
  background-color: #fff;
  justify-content: space-between;
  border-bottom: 5rpx solid #f1f1f1;
  position: relative;
  box-sizing: border-box;
  .content {
    position: relative;
    width: 100%;
    .detail-left {
      display: flex;
      .dessert-left {
        display: flex;
        align-items: center;
      }
      .dessert-size {
        width: 230rpx;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        margin-left: 20rpx;
        .dessert-price {
          font-size: 25rpx;
          color: #bb7755;
        }
      }
    }
    .detail-right {
      position: absolute;
      bottom: 0;
      right: 0;
      text {
        width: 50rpx;
        line-height: 50rpx;
        text-align: center;
        display: inline-block;
        background-color: #f1f1f1;
        margin-right: 10rpx;
      }
      .add {
        color: #f9acb4;
        border-radius: 10rpx 30rpx 30rpx 10rpx;
      }
      .sub {
        border-radius: 30rpx 10rpx 10rpx 30rpx;
      }
    }
  }
  .delete-btn {
    border-radius: 20rpx;
    background-color: #bb7755;
    color: #fff;
    width: 160rpx;
    text-align: center;
    height: 100%;
    position: absolute;
    top: 0;
    right: -160rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.fotter {
  width: 100%;
  height: 90rpx;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  .fotter-left {
    width: 70%;
    display: flex;
    justify-content: space-between;
    padding: 0 30rpx;
  }
  .fotter-right {
    width: 30%;
    line-height: 90rpx;
    background-color: #bb7755;
    text-align: center;
    color: #fff;
  }
}
</style>
